<?php
/**
 * Manages users account information
 * Allows to check if user is logged in or registered
 * 
 * @author paq
 *
 */
// FIXME: store read logged user object singleton
class Manager_User
{
	const PERMISSION_ADMIN 	= 'admin';
	const PERMISSION_USER	= 'user';
	const PERMISSION_GUEST 	= 'guest';
	
	protected function __construct()
	{	
	}
	
	public static function initialize()
	{
		$names = array(self::PERMISSION_ADMIN, self::PERMISSION_GUEST, self::PERMISSION_USER);
		
		$criteria = new Criteria();
		
		// add default admin user: login: admin, pass: admin
		if (UsersPeer::doCount(new Criteria()) === 0) {
			$admin = new Users();
			$admin->setLogin('admin')
				->setPassword('admin')
				->setEmail(Manager_SiteConfig::ADMIN_EMAIL)
				->setRegisterdate(time())
				->setUserspermissions(Manager_UserPermission::getAdmin())
				->setPreferencesgroups(Manager_PreferenceGroup::getDefault())
				->save();
		}
	}
	
	/**
	 * Login user
	 * Sets cookies
	 * 
	 * @param $user	user to login
	 * @return true if user was logged in; false if user was not logged in
	 */
	public static function login(Users $user)
	{
		// FIXME: zapisywanie w bazie jakiegos klucza dodatkowo potwierdzajacego
		// ze ktos jest zalogowany
		if (self::isInDatabase($user)) {
			if (setcookie('user', $user->getLogin(), time() + 7200)) {
				$user->setLastlogindate(time());
				$user->save();
				
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * Returns if user is logged in
	 * 
	 * @return TRUE if user is logged in; FALSE if user is not logged in
	 */
	public static function isLogged()
	{
		 if (isset($_COOKIE['user'])) {
		 	setcookie('user', $_COOKIE['user'], time() + 3600);
		 	
		 	return true;
		 }
		 
		 return false;
	}
	
	/**
	 * 
	 * @return string user login if some user is logged in; \
	 * FALSE if no user is logged in
	 */
	public static function getLogin()
	{
		if (self::isLogged()) {
			return $_COOKIE['user'];
		} else {
			return false;
		}
	}
	
	/**
	 * 
	 * @return Users logged in user; FALSE if user is not logged in
	 */
	public static function getUser()
	{
		if (self::isLogged()) {
			$login = self::getLogin();
			
			$criteria = new Criteria();
			$criteria->add(UsersPeer::LOGIN, $login, Criteria::EQUAL);
			
			return UsersPeer::doSelectOne($criteria);
		}
		
		return false;
	}
	
	/**
	 * 
	 * @param $login
	 * @param $password
	 * @return Users
	 */
	public static function get($login, $password)
	{
		$criteria = new Criteria();
		$criteria->add(UsersPeer::LOGIN, $login, Criteria::EQUAL)
			->add(UsersPeer::PASSWORD, md5($password), Criteria::EQUAL);
			
		return UsersPeer::doSelectOne($criteria);
	}
	
	/**
	 * Logs user out
	 * Deletes cookies
	 * 
	 * @return void
	 */
	public static function logout()
	{
		return setcookie('user', '', time() - 3600);
	}
	
	/**
	 * Checks if user with specified login and password is in the database
	 * 
	 * @param $user
	 * @return TRUE if user is in DB; false if specified user is not in DB
	 */
	public static function isInDatabase(Users $user)
	{
		$criteria = new Criteria();
		$criteria->add(UsersPeer::LOGIN, $user->getLogin(), Criteria::EQUAL);
		$criteria->add(UsersPeer::PASSWORD, $user->getPassword(), Criteria::EQUAL);
		
		$user = UsersPeer::doSelectOne($criteria);
		return !empty($user);
	}
	
	/**
	 * Checks if user with specified login is registered in DB
	 * 
	 * @param $user
	 * @return TRUE if specified user is in DB; FALSE if user is not in DB
	 */
	public static function isRegistered(Users $user)
	{
		$criteria = new Criteria();
		$criteria->add(UsersPeer::LOGIN, $user->getLogin(), Criteria::EQUAL);
		$user = UsersPeer::doSelectOne($criteria);
		
		return (!empty($user));
	}
	
	/**
	 * Returns specified user's  privilages
	 * 
	 * @param $login	user's login
	 * @return string one of constants User_Manager::PERMISSION_*
	 */
	// FIXME change name to LoginPermissions
	public static function getLoginPrivilages($login)
	{
		$criteria = new Criteria();
		$criteria->add(UsersPeer::LOGIN, $login, Criteria::EQUAL);
		$user = UsersPeer::doSelectOne($criteria);
		
		if (empty($user)) {
			return self::PERMISSION_GUEST;
		}
		
		return $user->getUserspermissions()->getName();
	}
	
	/**
	 * Checks if administrator is logged in
	 * User's login is retrieved from cookies
	 * 
	 * @return TRUE if admin is logged in; FALSE if admin is not logged in
	 */
	public static function isAdminLogged()
	{
		if (!self::isLogged()) {
			return false;
		}
		
		$login = self::getLogin();
		
		return (self::getLoginPrivilages($login) === self::PERMISSION_ADMIN);
	}
	
	/**
	 * 
	 * @param $privilageName
	 * @return Userspermissions
	 */
	public static function getPermission($privilageName)
	{
		$criteria = new Criteria();
		$criteria->add(UserspermissionsPeer::NAME, $privilageName, Criteria::EQUAL);
		
		$permission = UserspermissionsPeer::doSelectOne($criteria);
		
		if (empty($permission)) {
			throw new Exception($privilageName . ' permission does not exist.');
		}
		
		return $permission;
	}
	
	public static function onClick(Categories $category)
	{
		if (!self::isLogged()) {
			//throw new Exception('You are not logged in.');
			return;
		}
		
		$user = self::getUser();
		
		$criteria = new Criteria();
		$criteria->add(UsersPeer::ID_USER, $user->getIdUser(), Criteria::EQUAL);
		$criteria->add(CategoriesPeer::ID_CATEGORY, $category->getIdCategory(), Criteria::EQUAL);
		
		$userCategory = UserscategoriesclicksPeer::doSelectOne($criteria);
		
		if (empty($userCategory)) {
			$userCategory = new Userscategoriesclicks();
			$userCategory->setIdUser($user->getIdUser())
				->setIdCategory($category->getIdCategory());
		}
		
		$counter = $userCategory->getClickcounter() + 1;
		$userCategory->setClickcounter($counter)
			->save();
			
		$counter = $user->getClickcounter() + 1;
		$user->setClickcounter($counter);
		$user->save();
	}
}
